package nimble.security.sha;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;

public class SHAUtils {

    public static byte[] sha256(byte[] data)
    {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.reset();
            messageDigest.update(data);
            return messageDigest.digest();
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public static String sha256Hex(byte[] data)
    {
        byte[] result=sha256(data);
        if(!ObjectUtils.allNotNull(result))
        {
            return null;
        }
        return Hex.encodeHexString(result);
    }

    public static String sha256StringHex(String data)
    {
        if(StringUtils.isBlank(data))
        {
            return null;
        }
        try {
            byte[] dataBytes = data.getBytes(CharEncoding.UTF_8);
            return sha256Hex(dataBytes);
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
